package au.edu.unsw.editingtool.db;

import java.sql.SQLException;
import java.util.Hashtable;

import au.edu.unsw.editingtool.global.EditingToolException;

public class DBLoginpool extends DBManager {
	
	private String lid 	 = "";
	
	protected void setupDBMapping() {
		if (MappingTable.size() > 0)
			return;
		MappingTable.put("LoginPoolID", "lid");
		MappingTable.put("User", "user");
		MappingTable.put("SessionID", "sessionid");
		MappingTable.put("Date", "date");
		MappingTable.put("Publication", "pid");
	}
	
	public DBLoginpool() {
		this.table = "loginpool";
		this.primaryKeys = new String[]{"LoginPoolID"};
		this.setupDBMapping();
	}
	
	public void addRecord(Hashtable<String, String> newRecord) throws EditingToolException, SQLException, ClassNotFoundException {
		newRecord.put("Date", "CURRENT_TIMESTAMP()");
		this.setTable(this.table, "");
		this.setColumnValues(newRecord);
		
		this.initDB();
		this.insert(true, false);
		
		this.lid = this.getGenerateKey();
		this.clean();
	}
	
	public String getReturnKey() {
		return this.lid;
	}
	
	public boolean checkValid(String user, String sessionid, String lid) throws EditingToolException, ClassNotFoundException, SQLException {
		String fields[] = {"LoginPoolID"};
		
		this.setTable(this.table, "");
		
		if (user == null || sessionid == null || lid == null)
			return false;
		
		this.setFieldsCondition("User", this.setEqual(user));
		this.setFieldsCondition("SessionID", this.setEqual(sessionid));
		this.setFieldsCondition("LoginPoolID", this.setEqual(lid));
		this.addField(fields);
		
		this.initDB();
		this.selectRecords();
		if (this.ResultSet == null) {
			this.clean();
			return false;
		}
		boolean result = this.ResultSet.next();
		this.clean();
		return result;
	}
}
